package com.onpositive.mediawiki.propertyparser;

import java.util.List;

import org.eclipse.jface.text.Document;

import com.onpositive.richtext.model.BasePartition;
import com.onpositive.richtext.model.LinkPartition;
import com.onpositive.richtexteditor.model.ISimpleRichTextModel;

public class TextParagraphParser {
	
	public static String parse( String s )
	{		
		Document doc = new Document();
		MediaWikiTextLoader_dublicat loader = new MediaWikiTextLoader_dublicat(new DocumentWrapper(doc));
		ISimpleRichTextModel parsedModel ;
		try{
			parsedModel = loader.parse( s );
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			return s ;
		}
		List<BasePartition> partitions = parsedModel.getPartitions() ;
		StringBuilder builder = new StringBuilder() ;
		String text = parsedModel.getText();		
		
		if( partitions.size() > 0 )
		{			 
			for( BasePartition pt : partitions )
			{
				int offset = pt.getOffset();
				int length = pt.getLength();
				String str = text.substring( offset, offset + length ) ;
				
				if( pt instanceof LinkPartition )
				{
					LinkPartition lp = (LinkPartition) pt ;
					String url = lp.getUrl() ;
					builder.append("[[") ;
					
					if( !(str.equals(url)) ){
						builder.append( url) ;
						builder.append( "|") ;
					}
					
					builder.append( str) ;
					builder.append("]]") ;
				}
				else
					builder.append( str) ;
			}
			String txt2 = builder.toString();
			return txt2 ;
		}
		else
			return text ;		
	}
}
